package com.example.xiaomiao.Controller;

import com.example.xiaomiao.DTO.Return;
import com.example.xiaomiao.DO.User;
import com.example.xiaomiao.DTO.UpdateProfilePictureRequestDTO;
import com.example.xiaomiao.Service.UserService;
import com.example.xiaomiao.Util.JwtUtil;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

@RestController
@RequestMapping("/user")
public class UserController {
    @Resource
    UserService userService;

    @PostMapping("/update")
    public Return update(HttpServletRequest request, @RequestBody User new_message){
        String token = JwtUtil.getTokenFromCookie(request);
        String id = JwtUtil.extractUsername(token);
        int userId = Integer.parseInt(id.substring(8));
        return userService.update(userId,new_message);
    }

    @PostMapping("/updateProfilePicture")
    public Return updateProfilePicture(HttpServletRequest request, @RequestBody UpdateProfilePictureRequestDTO updatePictureRequestData){
        String token = JwtUtil.getTokenFromCookie(request);
        String id = JwtUtil.extractUsername(token);
        int userId = Integer.parseInt(id.substring(8));
        return userService.updateProfilePicture(userId,updatePictureRequestData);
    }

    @PostMapping("/get")
    public Return get(HttpServletRequest request){
        String token = JwtUtil.getTokenFromCookie(request);
        String id = JwtUtil.extractUsername(token);
        int userId = Integer.parseInt(id.substring(8));
        return userService.get(userId);
    }

    @PostMapping("/logout")
    public Return logout(HttpServletRequest request){
        String token = JwtUtil.getTokenFromCookie(request);
        String id = JwtUtil.extractUsername(token);
        int userId = Integer.parseInt(id.substring(8));
        return userService.logout(userId);
    }
}
